import {
    createEntityBase,
    loadAllBase,
    loadEntityBase,
    pageListBase,
    removeEntityBase,
    updateEntityBase
} from "../../../components/EntityApiBase.js";
import axios from "axios";
import {ElMessage} from "element-plus";

const basePath = import.meta.env.VITE_BACKEND_BASE_URL;

const entityPath = "/api/api";

async function loadEntity(id) {
    return await loadEntityBase(entityPath, id);
}

async function loadAll() {
    return await loadAllBase(entityPath);
}

async function pageList(paginationDTO) {
    return await pageListBase(entityPath, paginationDTO);
}

async function createEntity(entity) {
    return await createEntityBase(entityPath, entity);
}

async function updateEntity(id, entity) {
    return await updateEntityBase(entityPath, id, entity);
}

async function removeEntity(id) {
    return await removeEntityBase(entityPath, id);
}

async function apiAppRel(apiId, appIdList) {
    try {
        let {data} = await axios.post(basePath + entityPath + "/appRel/" + apiId, appIdList);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.error(error);
    }
}

async function getAppByApiId(appId) {
    try {
        let {data} = await axios(basePath + entityPath + "/appRel/" + appId);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.error(error);
    }
}

async function test(method, url, header, param, body) {
    try {
        let data = {};
        let config = {
            headers: header,
            params: method === 'GET' ? param : null
        };

        if (method === 'POST') {
            data = await axios.post(url, body, config);
        } else if (method === 'GET') {
            data = await axios.get(url, config);
        }
        return data.data;
    } catch (error) {
        console.log(error);
    }
}

export {loadEntity, loadAll, pageList, createEntity, updateEntity, removeEntity, apiAppRel, getAppByApiId, test};

